<template>
	<view class="container margin-lr">
		<view class="border-radius dflex-c bg-main padding-lr padding-tb-sm margin-top" @click="toHeadimg">
			<view class="dflex-c">
				<image class="border-radius-c headimg image-80 margin-right-xs " style="border: 1px solid #ccc;"
					:src="memberInfo.member_headimg || '../../../static/uni-check.png'"></image>
			</view>
		</view>
		<view class="border-radius margin-top-sm">
			<use-list-title title="昵称" iconfont=" " @goto="toEdit('member_nickname', '昵称', 15,false)" showArrow='true'
				:tip=" memberInfo.member_nickname || '未设置'"></use-list-title>
			<use-list-title title="姓名" iconfont=" " @goto="toEdit('member_truename', '姓名', 15,false)"
				:tip="memberInfo.member_truename || '未实名'"></use-list-title>
			<use-list-title title="性别" iconfont=" " @goto="toSwitch('gender')"
				:tip="(memberInfo.member_gender == 0 ? '未知' : memberInfo.member_gender == 1 ? '男' : '女') || '未知'">
			</use-list-title>
			<use-list-title title="手机号码" iconfont=" " @goto="toEdit('member_mobile', '手机号码', 11,false)"
				:tip="memberInfo.member_mobile || '未填写'"></use-list-title>

			<use-list-title title="邮箱" iconfont=" " @goto="toEdit('email', '邮箱', 20,false)"
				:tip="memberInfo.email || '未填写'">
			</use-list-title>
		</view>

		<view class="border-radius margin-top-sm bg-main">
			<view class="row dflex padding-lr padding-tb-sm" style="justify-content: space-between;opacity: 0.35;">
				<text class="tit">生日</text>
				<view class="dflex-c">
					<view class="ft-dark dflex-e" style="min-width: 95px;text-align: right;color: #5d5d5d;"
						@click="openCalendar">
						<text class="padding-right-xs fs-25 margin-right-xs">{{memberInfo.birthday||'未选择'}}
						</text>
						<uni-icons :size="16" class="uni-icon-wrapper" color="#bbb" type="arrowright" />
					</view>
				</view>
			</view>
		</view>
		<view class="padding-sm">
			<text class="fs-23 ft-dark-3">信息调整后请点击保存生效</text>
		</view>
		<view class=" margin-top-xl dflex-c w-full padding-tb-sm">
			<view class="btn wpre-65 border-radius-lg" @click="onSubmit">
				<text>保存</text>
			</view>
		</view>
		<view class="padding"></view>
		<l-clipper v-if="clipperShow" :image-url="memberInfo.member_headimg" :quality="0.6" @success="clipperSuccess"
			@cancel="clipperShow = false"></l-clipper>

		<use-popup :show="editShow" bgclass=" " mode="top" borderRadius="20" @open='openPopup' @close="closePopup('')">
			<view class="edit-area border-radius bg-main pos-r padding-bottom" style="overflow: visible;">
				<view class="pos-a " @click="editShow = false"
					style="right: 15px;top: 12.5px;height: 25px;width: 25px;line-height: 25px;">
					<uni-icons type="closeempty" size="21" color="#666" />
				</view>

				<view class="dflex-b ft-dark fs-xs margin-bottom-sm margin-lr-xs">
					<view>修改{{editTxt}}</view>
					<template if="editMaxLength!=='0'">
						<view>{{editVal.length}}/{{editMaxLength}}</view>
					</template>
				</view>
				<view class="dflex border-radius-sm field" style="padding: 18rpx 16rpx">
					<textarea class="fwb fs-sm" type="text" v-model="editVal" auto-height disable-default-padding
						style="max-height: 160rpx; min-height: 40rpx; height: 40rpx; font: initial;" :focus="editShow"
						confirm-type="done" :show-confirm-bar="false" cursor-spacing="20" placeholder="请输入"
						placeholder-class="fs-sm" :maxlength="editMaxLength" @confirm="editConfirm" />
				</view>

				<view class="bg-base margin-top-xl tac w-full border-radius-lg padding-tb-sm" @click.stop="editConfirm">
					确定
				</view>
			</view>
		</use-popup>
		<!-- 日历控件 -->
		<use-popup :show="calendarShow" bgclass=" " mode="bottom" borderRadius="20" @open='openPopup'
			@close="closePopup('')">
			<view class="share-area  border-top-radius bg-main">
				<view class="tac w-full padding-sm dflex-b">
					<text class="fs-blue" @click="calendarShow=false">取消</text>
					<text>
						<!-- 选择日期 -->
					</text>
					<text class="fs-blue" @click="onConfirm">完成</text>
				</view>
				<view class="uni-padding-wrap" style="display: none;">
					<view class="uni-title fs-20">
						日期：{{year}}年{{month}}月{{day}}日
					</view>
				</view>
				<view class="padding-lr  dflex-b pos-r">
					<picker-view v-if="visible" :indicator-style="indicatorStyle" :mask-style="maskStyle"
						:value="dateValue" @change="bindChange">
						<picker-view-column>
							<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</use-popup>
		<!-- 性别、职业 -->
		<use-action-sheet :show="actionSheetShow" :list="actionSheetList" :tips="actionSheetTips"
			@click="actionSheetClick" @close='closeSheet'></use-action-sheet>

		<!-- 地区 -->
		<use-address ref="useAddress" @onConfirm="changeAddr" cancelColor="#bbb" themeColor="#ff6a6c"></use-address>
	</view>
</template>

<script setup>
	import utils from '@/utils/util.js'
	import {
		reactive,
		ref,
		createApp,
		onMounted,
		getCurrentInstance
	} from "vue";

	import {
		storeToRefs
	} from 'pinia';
	import {
		useUserStore
	} from '@/store'

	const {
		ctx
	} = getCurrentInstance();
	console.log("ctx", ctx);
	const {
		proxy
	} = getCurrentInstance();
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app";

	let UserStore = useUserStore()
	/* 组件局部注册 */
	const app = createApp({});
	import lClipper from '@/components/lime-clipper/components/l-clipper/l-clipper';
	app.component({
		lClipper,
	});

	const date = new Date()
	const years = ref([])
	//const year = date.getFullYear()
	const year = ref('1980')
	const months = ref([])
	const month = ref(date.getMonth() + 1)
	const days = ref([])
	const day = ref(date.getDate())
	const dateValue = ref([1980, month.value - 1, day.value - 1])
	console.log(day)
	for (let i = 1980; i <= date.getFullYear(); i++) {
		years.value.push(i)
	}

	for (let i = 1; i <= 12; i++) {
		months.value.push(i)
	}

	for (let i = 1; i <= 31; i++) {
		days.value.push(i)
	}

	const clipperShow = ref(false)
	const editShow = ref(false)
	const editKey = ref('')
	const editVal = ref('')
	const editTxt = ref('')
	const editMaxLength = ref(30)
	const startDate = ref('')
	const endDate = ref('')
	const itemType = ref('')
	const actionSheetShow = ref(false)
	const actionSheetList = ref([])
	const actionSheetTips = ref({
		text: "",
		color: "#5a5a5a",
		size: 24
	})
	const genderList = ref([{
		text: "男",
		color: "#333"
	}, {
		text: "女",
		color: "#333"
	}])
	const clipper = ref('')
	const avatarId = ref('')
	const memberInfo = ref({
		member_headimg: '',
		member_truename: '',
		member_nickname: '',
		member_mobile: '',
		member_gender: '',
		member_rid: '',
		birthday: '',
		occupation: '',
		member_city: '',
		city_code: '',
		workAge: '',
		email: ''
	})
	// 日历控件
	const calendarShow = ref(false)
	const currentData = ref("")

	/**
	 * 解决动态设置indicator-style不生效的问题
	 */
	const visible = ref(true)
	const indicatorStyle = ref(`height: 50px;`)
	// #ifdef MP-KUAISHOU
	const maskStyle = ref("padding:10px 0")
	// #endif
	// #ifndef MP-KUAISHOU
	const maskStyle = ref("")
	// #endif

	const getDate = (type) => {
		const _date = new Date();

		let year = _date.getFullYear();
		let month = _date.getMonth() + 1;
		let day = _date.getDate();

		if (type === 'start') {
			year = year - 10;
		} else if (type === 'end') {
			year = year + 10;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;

		return `${year}-${month}-${day}`;
	}

	onLoad((option) => {
		uni.hideLoading();
		// if (!UserStore.member.islogin) {
		// 	proxy.$utils.msg('账号未登录');
		// 	return;
		// }
		loadData(() => {});
	})
	const maskClick = (e) => {
		console.log('----maskClick事件:', e);
	}
	const toHeadimg = (res) => {
		clipperShow.value = true;
	}
	const loadData = (callback) => {
		let url = proxy.$config.baseUrl;
		let params = {
			loading: false,
			url: '/api/ajax.ashx?oper=WX_GetUserCenter',
			method: 'get',
			data: {
				UnionId: UserStore.member.member_weixin
			}
		}

		proxy.$api.getData(url, params).then((res) => {
			console.log(res)
			if (res && res.status == "1") {
				try {
					let _info = res.info[0];
					memberInfo.value.member_headimg = _info.avatarurl;
					memberInfo.value.member_nickname = _info.nickname;
					memberInfo.value.member_name = _info.nickname;
					memberInfo.value.member_truename = _info.user_name;
					memberInfo.value.member_gender = _info.gender;
					memberInfo.value.member_mobile = _info.mobile_phone;
					memberInfo.value.email = _info.email;
					memberInfo.value.member_id = _info.userid;
					if (!_info.mobile_phone) return;
					decryptString(_info.mobile_phone, 'DecryptString');
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
				return;
			}
			proxy.$utils.msg('系统错误！');
		})

	}
	const onSubmit = () => {
		console.log(memberInfo.value)
		uni.showLoading({})
		updateUser();
	}
	const updateUser = (callback) => {
		let url = proxy.$config.baseTestUrl,
			_site = UserStore.CurrentSite.path;
		let params = {
			loading: false,
			url: '/' + _site + '/api/ajax.ashx?oper=WX_UpdateUserInfo',
			method: 'get',
			data: {
				UnionId: UserStore.member.member_weixin,
				avatar: memberInfo.value.member_headimg,
				nickName: memberInfo.value.member_nickname,
				realName: memberInfo.value.member_truename,
				gender: memberInfo.value.member_gender,
				phone: memberInfo.value.member_mobile,
				email: memberInfo.value.email
			}
		}

		proxy.$api.getData(url, params).then((res) => {
			console.log(res)
			uni.hideLoading()
			if (res && res.status == "1") {
				try {
					proxy.$utils.msg('保存成功！');
					// --保存成功后更新数据
					let _info = {
						member_headimg: memberInfo.value.member_headimg,
						member_name: memberInfo.value.member_truename,
						member_id: memberInfo.value.member_id,
						member_access_token: "",
						member_mobile: '',
						member_nickname: memberInfo.value.member_nickname,
						ORG: '',
						ORGID: '',
						member_weixin: UserStore.member.member_weixin,
						member_openid: UserStore.member.member_openid,
						member_rid: UserStore.member.member_rid,
						state: '',
						is_plus: ''
					}
					UserStore.putMember(_info);
					proxy.$utils.timerout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1750)
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
				return;
			}
			proxy.$utils.msg('系统错误！');
		})

	}
	const clipperSuccess = async (e) => {
		console.log('clipper上传成功：', e);
		let url = e.url,
			_site = UserStore.CurrentSite.path;
		uni.showLoading({
			title: '上传中'
		})
		// #ifdef H5
		url = URL.createObjectURL(await base64ToBlob({
			b64data: url,
			contentType: e.type
		}));
		// #endif
		console.log(url)
		uni.uploadFile({
			url: proxy.$config.baseTestUrl + '/' + _site + '/api/upload.ashx', //接口地址								
			filePath: url,
			name: 'file',
			formData: {
				'date': proxy.$utils.formatDate(new Date()),
				'fpath': "userAvatar",
				'fileType': e.type,
				'fileId': ''
			},
			//--header暂不设置，后台无法接收数据
			// header: {
			// 	"Content-Type": "multipart/form-data"
			// 	//"token": uni.getStorageSync('token'),
			// },
			//请求token
			success: (uRes) => {
				uni.hideLoading();
				console.log('uploadFile', uRes);
				let __uRes = JSON.parse(uRes.data);
				console.log(__uRes);
				if (__uRes.code == '1') {
					__uRes.url = __uRes.link;
					clipper.value = __uRes.fileId + "|" + __uRes.path + "|" + __uRes.name + "|" +
						__uRes.link;
					console.log("图片地址", __uRes.link)
					memberInfo.value.member_headimg = __uRes.link;
					console.log(memberInfo.value)
					utils.timerout(() => {
						clipperShow.value = false;
						uni.hideLoading();
					}, 250);

					try {
						URL.revokeObjectURL(url)
					} catch {}

				} else {
					uni.showToast({
						title: __uRes.msg,
						icon: 'none',
						duration: 2000
					})
					return
				}
			},
			fail: (err) => {
				console.log('use-upload', err);
				proxy.$utils.msg(err.message);
				uni.hideLoading();
			}
		})
	}
	// #ifdef H5
	const base64ToBlob = async ({
		b64data = '',
		contentType = 'image/png'
	} = {}) => {
		return new Promise((resolve, reject) => {

			try {
				const arr = b64data.split(',');
				const bytes = window.atob(arr[1]);
				const ua = new Uint8Array(new ArrayBuffer(bytes.length));
				for (let i = 0; i < bytes.length; i++) {
					ua[i] = bytes.charCodeAt(i);
				}

				resolve(new Blob([ua], {
					type: contentType
				}));
			} catch (e) {
				reject(e);
			}
		});
	}
	// #endif
	const openPopup = (state) => {}
	const closePopup = (type) => {
		calendarShow.value = false
	}
	const toEdit = (key, txt, len, bool) => {
		console.log(key, txt, len, bool)
		if (bool) return;
		let _val = memberInfo.value[key];
		console.log(_val, _val.length)
		editShow.value = true;
		editKey.value = key;
		editTxt.value = txt;
		editVal.value = _val;
		editMaxLength.value = len;
	}
	const editConfirm = () => {
		console.log(editKey.value)
		let data = {};
		data[editKey.value] = editVal.value.replace(/\n/g, '').replace(/\r\n/g, '').trim();
		if (!data[editKey.value]) {
			proxy.$utils.msg('请填写' + editTxt.value);
			return;
		}
		switch (editKey.value) {
			case 'member_nickname':
				memberInfo.value['member_nickname'] = data[editKey.value];
				break;
			case 'member_truename':
				memberInfo.value['member_truename'] = data[editKey.value];
				break;
			case 'email':
				let exg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/;

				if (!exg.test(data[editKey.value])) {
					proxy.$utils.msg('请输入正确的邮箱');
					return;
				}
				memberInfo.value[editKey.value] = data[editKey.value];
				break;
			default:
				memberInfo.value[editKey.value] = data[editKey.value];
		}
		utils.timerout(() => {
			editShow.value = false
		}, 250);
	}
	const openCalendar = () => {
		console.log(!memberInfo.value.birthday, dateValue.value)
		if (!memberInfo.value.birthday) {
			calendarShow.value = true;
			return;
		}
		let _val = memberInfo.value.birthday.split("/");
		let _index = (years.value).indexOf(Number(_val[0]));
		dateValue.value = [_index, Number(_val[1] - 1), Number(_val[2] - 1)];
		calendarShow.value = true;
	}
	const bindChange = (e) => {
		console.log(e)
		const val = e.detail.value;
		year.value = years.value[val[0]];
		month.value = months.value[val[1]];
		day.value = days.value[val[2]];
		currentData.value = years.value[val[0]] + "/" + months.value[val[1]] + "/" + days.value[val[2]];
	}
	const onConfirm = () => {
		console.log(memberInfo.value.birthday + "---" + currentData.value);
		if (memberInfo.value.birthday == currentData.value) {
			calendarShow.value = false;
			return
		};
		memberInfo.value.birthday = currentData.value;
		utils.timerout(() => {
			calendarShow.value = false
		}, 250);
	}
	const bindDateChange = (e) => {
		console.log(e);
		let data = {};
		data.birthday = e.detail.value;
		this.memberInfo.birthday = e.detail.value;
		this.updateUser(data, () => {
			this.loadData();
		})
	}
	const toSwitch = (type) => {
		switch (type) {
			case 'gender':
				actionSheetTips.value = {
					text: "选择性别",
					color: "#5a5a5a",
					size: 32
				}
				actionSheetList.value = genderList.value;
				break;
			case 'occupation':
				actionSheetTips.value = {
					text: "选择职业",
					color: "#5a5a5a",
					size: 32
				}
				actionSheetList.value = occupationList.value;
				break;
			default:
		}
		itemType.value = type;
		actionSheetShow.value = true;
	}
	// 点击操作菜单
	const closeSheet = () => {
		actionSheetShow.value = false
	}
	const actionSheetClick = (index) => {
		let _type = itemType.value;
		console.log(_type);
		let _text = actionSheetList.value[index].text;
		switch (_type) {
			case 'gender':
				if (memberInfo.value.member_gender == index + 1) return;
				memberInfo.value.member_gender = index + 1;

				break;
			case 'occupation':
				if (memberInfo.value.occupation == _text) return;
				memberInfo.value.occupation = _text;
				break;
			default:
		}
		utils.timerout(() => {
			actionSheetShow.value = false
		}, 250);
	}
	const toCity = () => {
		this.$refs.useAddress.open();
	}
	const changeAddr = (res) => {
		console.log(res);
		if (this.memberInfo.member_city == res.label) return;
		console.log('addr', res);
		this.memberInfo.member_city = res.label;
		this.memberInfo.city_code = res.areaCode;

	}
	const decryptString = (val, name) => { //解密
		let url = proxy.$config.baseTestUrl,
			_site = UserStore.CurrentSite.path;
		let params = {
			loading: false,
			url: '/' + _site + '/api/ajax.ashx?oper=' + name,
			method: 'post',
			data: {
				value: val
			}
		}
		console.log(params)
		const header_tmp = {
			"Authorization": "Bearer" + uni.getStorageSync("Access_token") || ''
		}
		proxy.$api.getData(url, params).then((res) => {
			console.log(res);
			if (res.statusCode == 200) {

			} else {
				console.log("解析错误")
			}
		})
	}
	onMounted(() => {
		startDate.value = getDate('start')
		endDate.value = getDate('end')
	})
</script>

<style lang='scss'>
	page {
		background: $page-color-base;
	}

	/* 日历控件 */
	picker-view {
		width: 100%;
		height: 600rpx;
		margin-top: 20rpx;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	.edit-area {
		width: 80vw;
		padding: 100rpx 80rpx 45rpx 80rpx;
		margin-top: 20vh;
		margin-left: 10vw;
		margin-right: 10vw;
		margin-bottom: 5px;

		.field {
			background-color: #f5f5f5;
		}
	}

	.oper-area {
		width: 80vw;
		padding: 80rpx;
		padding-top: 100rpx;
		margin-top: 20vh;
		margin-left: 10vw;

		.field {
			background-color: #f5f5f5;
		}
	}
</style>